﻿using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.DAL;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;

namespace Ledict.ConditionExtract.BLL
{
    public class NodeTree_ArgumentTypeBLL
    {
        ArgumentTypeDAL argumenttypedal = new ArgumentTypeDAL();
        ArgumentDAL argumentdal = new ArgumentDAL();
        XmlLabel_SuitTypeRelDAL suittype = new XmlLabel_SuitTypeRelDAL();
        NewIDDAL newiddal = new NewIDDAL();
        CaseCauseBLL casecausebll = new CaseCauseBLL();

        public string Exists(SYS_ArgumentType Model)
        {
            return argumenttypedal.Exists(Model);
        }

        public decimal GetAT_ShowIndex()
        {
            return argumenttypedal.GetAT_ShowIndex();
        }

        /// <summary>
        /// 获取字典编号
        /// </summary>
        /// <param name="ccId"></param>
        /// <returns></returns>
        public string GetArgumentTypeNumber(string ccId,string ccName,string argumentName)
        {
            return argumenttypedal.GetArgumentTypeNumber(ccId,ccName, argumentName);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public void Add(SYS_ArgumentType Model)
        {
            Model.AT_MatchKeyWord = Model.AT_MatchKeyWord.Replace("\n", "");
            //1、添加SYS_ArgumentType 
            argumenttypedal.Add(Model);
            #region 2、添加SYS_Argument
            //确保两表统一，先删后增
            if (argumentdal.Exists(Model.AT_ID))
                argumentdal.Delete(Model.AT_ID);
            Model.AT_MatchKeyWord = System.Text.RegularExpressions.Regex.Replace(Model.AT_MatchKeyWord, "[,，].*?(?=(；|;|$))", "");//只留下最标准的字典值
            MatchCollection Argumentmatch = System.Text.RegularExpressions.Regex.Matches(Model.AT_MatchKeyWord, @"(?<=;|；|^)(.*?)=(.*?)(?=;|；|$)");//分解成单个字典值
            foreach (Match str in Argumentmatch)
            {
                SYS_Argument ArgumentModel = new SYS_Argument();
                ArgumentModel.AM_ID = newiddal.JudgeDoc_CreateID("SYS_Argument");
                ArgumentModel.AT_ID = Model.AT_ID;
                ArgumentModel.AM_Code = str.Groups[1].ToString();
                ArgumentModel.AM_Name = str.Groups[2].ToString();
                ArgumentModel.AM_ShowIndex = argumentdal.GetShowIndex();
                argumentdal.Add(ArgumentModel);

                var isSuittypeHas = false;
                //查询suittype
                var oldSuitTypeDt = suittype.GetSuitTypeList(Model.AT_CauseID);
                if (oldSuitTypeDt != null && oldSuitTypeDt.Rows.Count > 0)
                    isSuittypeHas = true;
                if (Model.AT_Name.Contains("诉讼请求种类"))
                {
                    if (isSuittypeHas)
                    {
                        //更新
                        if (IsHasSuitTypecode(oldSuitTypeDt, str.Groups[1].ToString().Trim()))
                        {
                            suittype.Update_SYS_SuitType_suitTypecode(Model.AT_CauseID, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                        }
                        else //添加
                        {
                            suittype.Add_SYS_SuitType_suitTypecode(Model.AT_CauseID, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                        }


                    }
                    else //不存在
                    {
                        suittype.Add_SYS_SuitType_suitTypecode(Model.AT_CauseID, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                    }
                }
            }

            #endregion
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public void AddArgument(SYS_ArgumentType Model)
        {
            Model.AT_MatchKeyWord = Model.AT_MatchKeyWord.Replace("\n", "");
            //1、添加SYS_ArgumentType 
            argumenttypedal.Add(Model);
            #region 2、添加SYS_Argument
            //确保两表统一，先删后增
            if (argumentdal.Exists(Model.AT_ID))
                argumentdal.Delete(Model.AT_ID);
            Model.AT_MatchKeyWord = System.Text.RegularExpressions.Regex.Replace(Model.AT_MatchKeyWord, "[,，].*?(?=(；|;|$))", "");//只留下最标准的字典值
            MatchCollection Argumentmatch = System.Text.RegularExpressions.Regex.Matches(Model.AT_MatchKeyWord, @"(?<=;|；|^)(.*?)=(.*?)(?=;|；|$)");//分解成单个字典值
            foreach (Match str in Argumentmatch)
            {
                SYS_Argument ArgumentModel = new SYS_Argument();
                ArgumentModel.AM_ID = newiddal.JudgeDoc_CreateID("SYS_Argument");
                ArgumentModel.AT_ID = Model.AT_ID;
                ArgumentModel.AM_Code = str.Groups[1].ToString();
                ArgumentModel.AM_Name = str.Groups[2].ToString();
                ArgumentModel.AM_ShowIndex = argumentdal.GetShowIndex();
                argumentdal.Add(ArgumentModel);

                var isSuittypeHas = false;
                //查询suittype
                var oldSuitTypeDt = suittype.GetSuitTypeList(Model.AT_CauseID);
                if (oldSuitTypeDt != null && oldSuitTypeDt.Rows.Count > 0)
                    isSuittypeHas = true;
                if (Model.AT_Name.Contains("诉讼请求种类"))
                {
                    if (isSuittypeHas)
                    {
                        //更新
                        if (IsHasSuitTypecode(oldSuitTypeDt, str.Groups[1].ToString().Trim()))
                        {
                            suittype.Update_SYS_SuitType_suitTypecode(Model.AT_CauseID, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                        }
                        else //添加
                        {
                            suittype.Add_SYS_SuitType_suitTypecode(Model.AT_CauseID, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                        }


                    }
                    else //不存在
                    {
                        suittype.Add_SYS_SuitType_suitTypecode(Model.AT_CauseID, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                    }
                }
            }

            #endregion
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public void Delete(string AT_ID)
        {

            //删除SYS_ArgumentType 
            argumenttypedal.Delete(AT_ID);
            //删除SYS_Argument
            argumentdal.Delete(AT_ID);

        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool DeleteSysArgumentType(string AT_CauseID)
        {
            return argumenttypedal.DeleteSysArgumentType(AT_CauseID);
        }

        /// <summary>
        /// 更新ArgumentType
        /// </summary>
        /// <param name="model">模型</param>
        /// <param name="ccId">情形情节ID</param>
        public void Update(SYS_ArgumentType model, string ccId = null)
        {

            model.AT_MatchKeyWord = model.AT_MatchKeyWord.Replace("\n", "");
            //1、SYS_ArgumentType 
            argumenttypedal.Update(model);
            //判断对应的诉请要素种类是否存在
            var isSuittypeHas = false;
            //查询suittype
            var oldSuitTypeDt = suittype.GetSuitTypeList(ccId);
            if (oldSuitTypeDt != null && oldSuitTypeDt.Rows.Count > 0)
                isSuittypeHas = true;


            #region 2、SYS_Argument
            //确保两表统一，先删后增
            if (argumentdal.Exists(model.AT_ID))
                argumentdal.DeleteByAtId(model.AT_ID);
            model.AT_MatchKeyWord = System.Text.RegularExpressions.Regex.Replace(model.AT_MatchKeyWord, "[,].*?(?=(；|;|$))", "");//只留下最标准的字典值
            MatchCollection argumentmatch = System.Text.RegularExpressions.Regex.Matches(model.AT_MatchKeyWord, @"(?<=;|；|^)(.*?)=(.*?)(?=;|；|$)");//分解成单个字典值
            foreach (Match str in argumentmatch)
            {
                var argumentModel = new SYS_Argument
                {
                    AM_ID = newiddal.JudgeDoc_CreateID("SYS_Argument"),
                    AT_ID = model.AT_ID,
                    AM_Code = str.Groups[1].ToString().Trim(),
                    AM_Name = str.Groups[2].ToString(),
                    AM_ShowIndex = argumentdal.GetShowIndex()
                };
                argumentdal.Add(argumentModel);

                if (string.IsNullOrEmpty(ccId))
                    continue;

                //存在诉请种类
                if (model.AT_Name.Contains("诉讼请求种类"))
                {
                    if (isSuittypeHas)
                    {
                        //更新
                        if (IsHasSuitTypecode(oldSuitTypeDt, str.Groups[1].ToString().Trim()))
                        {
                            suittype.Update_SYS_SuitType_suitTypecode(ccId, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                        }
                        else //添加
                        {
                            suittype.Add_SYS_SuitType_suitTypecode(ccId, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                        }


                    }
                    else //不存在
                    {
                        suittype.Add_SYS_SuitType_suitTypecode(ccId, str.Groups[1].ToString().Trim(), str.Groups[2].ToString());
                    }
                }

            }
            if (model.AT_Name.Contains("诉讼请求种类"))
            {
                //最后删除不需要的记录
                var newSuitTypeDt = suittype.GetSuitTypeList(ccId);
                DeleteSuitTypeCode(newSuitTypeDt, argumentmatch);
            }


            #endregion

        }

        /// <summary>
        /// 判断是否存在指定的code（诉请种类中）
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="suitTypecode"></param>
        /// <returns></returns>
        private bool IsHasSuitTypecode(DataTable dt, string suitTypecode)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["SuitTypecode"].ToString().Equals(suitTypecode))
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 最后删除不需要的记录
        /// </summary>
        /// <param name="newDt"></param>
        /// <param name="matchCollection"></param>
        private void DeleteSuitTypeCode(DataTable newDt, MatchCollection matchCollection)
        {

            for (int i = 0; i < newDt.Rows.Count; i++)
            {
                var isHasCode = false;
                foreach (Match match in matchCollection)
                {
                    if (newDt.Rows[i]["SuitTypecode"].ToString().Equals(match.Groups[1].ToString().Trim()))
                        isHasCode = true;
                }

                //新数据里不存在，则删除
                if (!isHasCode)
                {
                    suittype.Delete_SYS_SuitType_suitTypecode(newDt.Rows[i]["ST_ID"].ToString());
                }

            }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataTable GetList(string AT_CauseID, string SelectArgument)
        {
            return argumenttypedal.GetList(AT_CauseID, SelectArgument);
        }
        public SYS_ArgumentType GetMatchKeyWord(string AT_Code)
        {
            return argumenttypedal.GetMatchKeyWord(AT_Code);
        }

        public string IsExistMatchKeyWordCode(string CC_ID)
        {
            string matchValueCode = "";
            //XMLpath
            SYS_CaseCause model1 = casecausebll.GetCaseCauseByCCID(CC_ID);
            // model.XmlPath 
            //案由XML属性
            string ConfigXML = "";
           // ConfigXML = casecausebll.GetCauseConfigXML(CC_ID);
            string webapiUrl1 = ConfigHelper.AppSettings("xmlPath") + "/system/config/v1/getfilecontent";
            RequestContent rc = new RequestContent() { systemName = "Ldt_JudgeDocSystem", moudleName = "SYS_CaseCause\\ConfigXML", fileType = "xml", fileName = casecausebll.IsParentRealation1(CC_ID).CC_ID };
            ComResult model = WebUtil.DoPost<ComResult>(webapiUrl1, rc, "utf-8");
            if (model.result.code == "1")
            {
                ConfigXML = model.body.content;
            }
            //提取编号
            if (ConfigXML != "")
            {
                XmlDocument document = new XmlDocument();
                document.LoadXml(ConfigXML);
                XmlNodeList nodes = document.SelectNodes(string.Format("/elementConfig/element[@xmlPath='{0}']/sourceContent", model1.XmlPath));
                if (0 < nodes.Count)
                {
                    matchValueCode = nodes[0].InnerText;
                }
            }
            return matchValueCode;
        }

    }
}
